import cv2 as cv
import numpy as np

# 卷积是深度学习的核心基础，充分理解卷积计算原理。二维卷积计算底层编程，代码按下列要求完成：（20分）
# （15）参照下图定义图像image和核函数kernel矩阵
image = np.uint8([
    [3, 0, 1, 2, 7, 4],
    [1, 5, 8, 9, 3, 1],
    [2, 7, 2, 5, 1, 3],
    [0, 1, 3, 1, 7, 8],
    [4, 2, 1, 6, 2, 8],
    [2, 4, 5, 2, 3, 9]
])

kernel = np.float32([
    [1, 0, -1],
    [1, 0, -1],
    [1, 0, -1]
])


# （16）用函数cal_convoluation_size（）计算卷积尺寸
def cal_convolution_size(size, kernel_size):
    return size + 1 - kernel_size


# （17）用函数convoluation(image, kernel)计算卷积结果
def convolution(image, kernel):
    shape = image.shape
    h = shape[0]
    w = shape[1]
    k_shape = kernel.shape
    kh = k_shape[0]
    kw = k_shape[1]
    kh2 = kh // 2
    kw2 = kw // 2
    res_h = cal_convolution_size(h, kh)
    res_w = cal_convolution_size(w, kw)
    res_mat = np.zeros((res_h, res_w), dtype=np.float32)
    for i in range(res_h):
        for j in range(res_w):
            res = 0.
            for ii in range(kh):
                for jj in range(kw):
                    res += image[ii + i, jj + j] * kernel[ii, jj]
            res_mat[i, j] = res
    return res_mat

# （18）调用函数convoluation，返回计算结果并打印输出
res_mat = convolution(image, kernel)
print('调用函数convoluation，返回计算结果并打印输出:')
print(res_mat)
